package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.minio.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.nntp.Article;
import org.apache.hbase.thirdparty.com.google.protobuf.ByteInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jack
 * @data 2024 15:49
 */
@Service
@Transactional
@Slf4j
public class FreemarkerServiceImpl implements FreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 构建文章详情页
     *
     * @param articleDto
     */
    @Override
    public void buildPage(ArticleDto articleDto) {
        try {
            //1. 拿到数据
            String content = articleDto.getContent();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("content", JSONArray.parseArray(content));

            //2. 拿到模板
            Template template = configuration.getTemplate("article.ftl");

            //3. 合成完整页面，并将合成后的页面数据用StringWriter暂存
            StringWriter writer = new StringWriter();
            template.process(dataMap,writer);

            //4. 将StringWriter中的数据上传到minIO
            ByteArrayInputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", String.valueOf(articleDto.getId()), is);

            //5. 将minIO返回的url回填到ap_article表的static_url字段上
            ApArticle article = new ApArticle();
            article.setId(articleDto.getId());
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
